package main

import (
	"golang.org/x/net/websocket"
	"fmt"
	"net/http"
	"os"
	"html/template"
	"net"
	. "weosocket/broadcaster"
)
var (
	HTTP_HOST = ":8000"
)
func Http_Hander(ws *websocket.Conn) {
	fmt.Printf("New Accept: %s" , ws.RemoteAddr())
	ch := make(chan bool)
	go HandleConn(ws , ch)
	<- ch
}
func Find_Ipv4_Addr() string {
	addrs , err := net.InterfaceAddrs()
	if err != nil {
		fmt.Println(err)
		os.Exit(1)
	}
	for _ , address := range addrs {
		if ipnet , ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() && ipnet.IP.To4() != nil{
			return ipnet.IP.String();
		}
	}
	return ""
}
func Start(w http.ResponseWriter , r *http.Request) {
	dir , _ := os.Getwd()
	dir += "\\client.html"
	temp1 , err := template.ParseFiles(dir)
	if err != nil {
		fmt.Println("ParseFiles error!" , err)
		return
	}
	ipv4 := Find_Ipv4_Addr()
	temp1.Execute(w , ipv4)
}
func main() {
	go Broadcaster()
	http.HandleFunc("/" , Start)
	http.Handle("/chat" , websocket.Handler(Http_Hander))
	if err := http.ListenAndServe(HTTP_HOST , nil); err != nil {
		panic(err)
	}
}